# coding: utf-8
logsFolder = "logs"
searches = ("Bad Rcon", "HLBrute") #searches = ("Reda", "connected")

printIp = False

writeToFile = True
listip_cfg = "cfg/listip.cfg"


import os
def main(search, ip=False):
    searchLines = len(search)
    ipList = []

    if not os.path.exists(logsFolder):
        print "Папка с логами отстутствует (или неправильно задана)"
    else:
        list_files = os.listdir(logsFolder)

        for file in list_files:

            file = open(logsFolder + "/" + file, 'r')

            for line in file:
                if searchLines > 1:
                    if search[0] in line and search[1] in line:
                        if ip:
                            params = line.split()
                            lastElementIndex = len(params) - 1
                            if "HLBrute" in line or "disconnected" not in line and "address" in line:
                                str_ipPlusPort = params[lastElementIndex].strip('"')
                                #print str_ipPlusPort
                                indexOfDoublePunktum = str_ipPlusPort.index(":")
                                str_ip = str_ipPlusPort[:indexOfDoublePunktum]
                                ipList.append(str_ip)

                        else:
                            print line
                else:

                    if search[0] in line:
                        print line

            file.close()
    return ipList

def writeToLogFile(IPset, file):

    try:
        cfgFile = open(file, "a")
    except:
        cfgFile = open("cfg/listip.cfg", "a")

    for ip in IPset:
        cfgFile.write("addip 0.0 %s \n" % ip)

    cfgFile.close()


if __name__ == "__main__":
    if not printIp and writeToFile:
        print "Пишем в файл но нет вывода в IP!"
        printIp = True

    ips = main(searches, printIp)

    if writeToFile:
        ips = set(ips)
        writeToLogFile(ips, listip_cfg)
    else:
        for i in ips:
            print i
